// pages/addDoctor/addDoctor.js
Page({
  data: {
    userDoctor: { //医生账号信息
      admin: '',
      name: '',
      pwd: '',
    },
    doctorInfo: { //医生信息
      doctorName: '',
      doctorId: '',
      doctorPosition: '',
      doctorPay: null,
      doctorMaxPatient: null,
      doctorStartTime: '',
      doctorEndTime: '',
      doctorExpertise: '',
      doctorPic: [],
      userDoctorAdmin: '',
      userDoctorName: '',
      userDoctorPwd: '',
      doctorImage: '',
    },
    isCommit: false, //是否提交了，用于下载时删除云存储图片判断用
    isChange: false, //是否是修改，如果是修改，在页面跳转进来时改成true,并从数据库拿数据，走的时候不用删除云存储库,提交的时候修改
    idNoOne: false,
  },
  //页面刚进来时(用来判断时修改还是添加)
  onLoad(options) {
    var that = this
    console.log('从管理医师信息页面进来时带的医生账号', options.admin)
    //如果是修改
    if (options.admin) {
      // isChange改成true
      that.setData({
        isChange: true,
      })
      //从数据库拿数据
      wx.cloud.callFunction({
        name: "doctorInfo",
        data: {
          action: "findOne",
          userDoctorAdmin: options.admin
        }
      }).then(res => {
        console.log('拿数据库的数据成功', res)
        //把数据库拿到的数据存放到本地
        var admin = "userDoctor.admin"
        var name = "userDoctor.name"
        var pwd = "userDoctor.pwd"
        that.setData({
          doctorInfo: res.result.data[0],
          [admin]: res.result.data[0].userDoctorAdmin,
          [name]: res.result.data[0].userDoctorName,
          [pwd]: res.result.data[0].userDoctorPwd,
        })
      }).catch(res => {
        console.log('拿数据库的数据失败', res)
      })
    }
  },
  //页面返回时（卸载时），用来删除没有提交到数据库的云存储图片
  onUnload() {
    if (!this.data.isCommit && !this.data.isChange) { //如果没有提交就返回，则删除云存储图片
      console.log('卸载，用来删除没有提交到数据库的云存储图片')
      console.log('将要删除的云存储列表，也就是现有的本地图片地址信息', this.data.doctorInfo.doctorPic)
      //进行云存储删除操作
      wx.cloud.deleteFile({
        fileList: this.data.doctorInfo.doctorPic
      }).then(res => {
        console.log('成功！已将之前上传到云存储的图片在云存储删除', res)
      }).catch(error => {
        console.log('失败！没有之前上传到云存储的图片在云存储删除', error)
      })
    }
  },

  //获取输入的值
  //医师账号：
  getadmin(e) {
    var admin = "userDoctor.admin"
    var userDoctorAdmin = "doctorInfo.userDoctorAdmin"
    console.log(e.detail.value)

    this.setData({
      [admin]: e.detail.value,
      [userDoctorAdmin]: e.detail.value
    })

  },
  //医师用户名
  getname(e) {
    var name = "userDoctor.name"
    var userDoctorName = "doctorInfo.userDoctorName"
    console.log(e.detail.value)

    this.setData({
      [name]: e.detail.value,
      [userDoctorName]: e.detail.value
    })

  },
  //医师初始密码
  getpwd(e) {
    var pwd = "userDoctor.pwd"
    var userDoctorPwd = "doctorInfo.userDoctorPwd"
    console.log(e.detail.value)

    this.setData({
      [pwd]: e.detail.value,
      [userDoctorPwd]: e.detail.value,
    })

  },


  //医师姓名：
  getdoctorName(e) {
    var doctorName = "doctorInfo.doctorName"
    console.log(e.detail.value)

    this.setData({
      [doctorName]: e.detail.value
    })

  },
  //医师id：
  getdoctorId(e) {
    var doctorId = "doctorInfo.doctorId"
    console.log(e.detail.value)

    this.setData({
      [doctorId]: e.detail.value
    })

  },
  //医师职位：
  getdoctorPosition(e) {
    var doctorPosition = "doctorInfo.doctorPosition"
    console.log(e.detail.value)

    this.setData({
      [doctorPosition]: e.detail.value
    })

  },
  //预约费用：
  getdoctorPay(e) {
    var doctorPay = "doctorInfo.doctorPay"
    console.log(e.detail.value)
    this.setData({
      [doctorPay]: e.detail.value
    })
  },
  //可约人数：
  getdoctorMaxPatient(e) {
    var doctorMaxPatient = "doctorInfo.doctorMaxPatient"
    console.log(e.detail.value)

    this.setData({
      [doctorMaxPatient]: e.detail.value
    })

  },
  //【开始时间】
  getdoctorStartTime(e) {
    var doctorStartTime = "doctorInfo.doctorStartTime"
    console.log(e.detail.value)

    this.setData({
      [doctorStartTime]: e.detail.value
    })

  },
  //【结束时间】
  getdoctorEndTime(e) {
    var doctorEndTime = "doctorInfo.doctorEndTime"
    console.log(e.detail.value)

    this.setData({
      [doctorEndTime]: e.detail.value
    })

  },
  //医师专长：
  getdoctorExpertise(e) {
    var doctorExpertise = "doctorInfo.doctorExpertise"
    console.log(e.detail.value)

    this.setData({
      [doctorExpertise]: e.detail.value.replace(/\s+/g, '')
    })

  },

  //添加医师本地照片(0选择1云存储2本地）
  addDoctorPic() {
    let that = this
    //0选择图片
    wx.chooseImage({
      success(res) {
        console.log("0选择图片成功，选择的图片的信息", res)
        const ImageUrl = res.tempFilePaths[0] //图片临时地址
        let suffix = /\.[^\.]+$/.exec(ImageUrl)[0]; // 正则表达式，获取图片扩展名
        console.log('0选择的图片的临时url', ImageUrl)
        console.log('0选择的图片文件扩展名', suffix)
        //1把这张图传到云存储
        wx.cloud.uploadFile({
            count: 1,
            cloudPath: 'doctorPic/' + new Date().getTime() + suffix,
            filePath: ImageUrl
          },
          //1上传中提示
          wx.showLoading({
            title: '图片上传中...',
          })
        ).then(res => {
          console.log('1上传图片到云存储成功，图片的id是', res.fileID)
          //2把这张图片云存储id传到本地
          var i = that.data.doctorInfo.doctorPic.length //添加图片之前的图片数量
          var doctorPic = 'doctorInfo.doctorPic[' + i + ']'
          that.setData({
            [doctorPic]: res.fileID,
          })
          console.log('2添加图片后的本地诊所信息', that.data.doctorInfo)
          setTimeout(() => {
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '上传图片成功',
                })
              },
            })
          }, 1000);
        }).catch(error => {
          console.log('1上传图片到云存储失败', error)
          wx.hideLoading({
            success: (res) => {
              wx.showToast({
                icon: 'none',
                title: '上传图片失败',
              })
            },
          })
        })
      }
    })
  },
  //删除医生本地照片((00选择11云存储22本地）
  delDoctorPic: function (e) {
    console.log('picid', e.currentTarget.dataset.picid)
    var that = this
    //00删除确认
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗',
      success(res) {
        if (res.confirm) {
          console.log('00用户点击确定')
          //00删除中提示
          wx.showLoading({
            title: '正在删除...',
          })
          //11删除云存储文件
          wx.cloud.deleteFile({
            fileList: [e.currentTarget.dataset.picid]
          }).then(res => {
            console.log('11删除云文件成功', res.fileList)
            //22删除本地图片
            var doctorPic = 'doctorInfo.doctorPic'
            for (var i = 0; i < that.data.doctorInfo.doctorPic.length; i++) { //循环现有本地图片数组
              if (that.data.doctorInfo.doctorPic[i] === e.currentTarget.dataset.picid) { //比对本地图片数组中和所选图片一致的下标
                that.data.doctorInfo.doctorPic.splice(i, 1) //利用splice在本地删除对应下标的图片，是的原数组改变为新数组！
                that.setData({
                  [doctorPic]: that.data.doctorInfo.doctorPic
                })
              }
            }
            console.log('22删除后本地图片数组', that.data.doctorInfo.doctorPic)
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  title: '删除成功',
                })
              },
            })

          }).catch(error => {
            console.log('11删除云文件失败', error)
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  icon: 'none',
                  title: '删除图片失败',
                })
              },
            })
          })
        } else if (res.cancel) {
          console.log('00用户点击取消')
        }
      }
    })
  },


  //提交
  commitA() {
    var that = this
    wx.showLoading({
      title: '医师新建中...',
    })

    //验证必填（9）
    wx.cloud.database().collection('doctorInfo').where({
      doctorId: that.data.doctorInfo.doctorId
    }).get({
      success: function (res) {
        console.log(111, res.data[0].doctorId)
        if (res.data[0].doctorId) {
          that.setData({
            idNoOne: true
          })
          console.log('idNoOne', that.data.idNoOne)
        }
      }
    })
    //给延时的原因：上面的查询医师Id是否唯一是云操作，需要时间
    setTimeout(()=>{
      if (!this.data.doctorInfo.doctorName) {
        wx.showToast({
          icon: 'none',
          title: '医师姓名不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorId) {
        wx.showToast({
          icon: 'none',
          title: '医师id不能为空',
        })
        return
      }
      //验证医师id是否被用过，保证医师id的唯一性
      if (that.data.idNoOne) {
        console.log('oidididididididididididididi')
        wx.showToast({
          icon: 'none',
          title: '此id已被使用，请重新输入Id',
        })
        this.setData({
          idNoOne: false
        })
        console.log(that.data.idNoOne)
        return
      }
      if (!this.data.doctorInfo.doctorPosition) {
        wx.showToast({
          icon: 'none',
          title: '医师职位不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorPay) {
        wx.showToast({
          icon: 'none',
          title: '预约费用不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorMaxPatient) {
        wx.showToast({
          icon: 'none',
          title: '可约人数不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorStartTime) {
        wx.showToast({
          icon: 'none',
          title: '开始时间不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorEndTime) {
        wx.showToast({
          icon: 'none',
          title: '结束时间不能为空',
        })
        return
      }
      if (!this.data.doctorInfo.doctorExpertise) {
        wx.showToast({
          icon: 'none',
          title: '医师专长不能为空',
        })
        return
      }
      if (this.data.doctorInfo.doctorPic.length == 0) {
        wx.showToast({
          icon: 'none',
          title: '医师图片不能为空',
        })
        return
      }
      //1注册医师（10从数据库获取user信息11得到数据的user信息12注册）
      //得到输入的各项值
      let name = that.data.userDoctor.name
      let admin = that.data.userDoctor.admin
      let pwd = that.data.userDoctor.pwd
      //校验输入的各项值
      if (admin.length < 3) {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '账号不能少于3个字符',
            })
          },
        })
        return
      }
      if (name.length < 2) {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '用户名不能低于2个字符',
            })
          },
        })
        return
      }
      if (pwd.length < 6) {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '密码不能少于6个字符',
            })
          },
        })
        return
      }
      //验证账号是否被用过，保证账号的唯一性
      wx.cloud.database().collection('user').where({
        admin: admin //到云数据库找与本地输入的账号相同的账号的那条信息
      }).get({
        success(res) {
          console.log('10数据获取成功', res)
          let user = res.data[0] //到user数据库获取与输入账号对应的个人信息到user变量
          console.log('11user', user)
          if (!user) { //如果该账号没有被注册过，开始真正的注册
            //把输入的值传到云数据库
            wx.cloud.database().collection('user').add({
              data: {
                name: name,
                admin: admin,
                pwd: pwd,
                userType: 'B'
              },
              success(res) {
                console.log("12注册成功", res)
                //2提交图片文字信息
                wx.cloud.callFunction({
                  name: "doctorInfo",
                  data: {
                    action: "add",
                    doctorName: that.data.doctorInfo.doctorName,
                    doctorId: that.data.doctorInfo.doctorId,
                    doctorPosition: that.data.doctorInfo.doctorPosition,
                    doctorPay: parseFloat(that.data.doctorInfo.doctorPay),
                    doctorMaxPatient: parseInt(that.data.doctorInfo.doctorMaxPatient, 10),
                    doctorStartTime: that.data.doctorInfo.doctorStartTime,
                    doctorEndTime: that.data.doctorInfo.doctorEndTime,
                    doctorExpertise: that.data.doctorInfo.doctorExpertise,
                    doctorPic: that.data.doctorInfo.doctorPic,
                    userDoctorAdmin: that.data.doctorInfo.userDoctorAdmin,
                    userDoctorName: that.data.doctorInfo.userDoctorName,
                    userDoctorPwd: that.data.doctorInfo.userDoctorPwd,
                  }
                }).then(res => {
                  console.log('21新建医师信息和账户成功', res)
                  //提交之后的提交标志变为true
                  that.setData({
                    isCommit: true
                  })
                  console.log('提交后的isCommit是', that.data.isCommit)
                  wx.hideLoading({
                    success: (res) => {
                      wx.showToast({
                        title: '新建医师成功',
                      })
                      setTimeout(function () {
                        wx.navigateBack({})
                      }, 1000)
                    },
                  })
                }).catch(res => {
                  console.log('21医师信息提交失败', res)
                  wx.hideLoading({
                    success: (res) => {
                      wx.showToast({
                        icon: 'none',
                        title: '新建医师失败',
                      })
                    },
                  })
                })
              },
              fail(res) {
                console.log('12注册失败', res)
                wx.hideLoading({
                  success: (res) => {
                    wx.showToast({
                      icon: 'none',
                      title: '注册失败',
                    })
                  },
                })
              }
            })
          } else {
            console.log('11账号已经存在')
            wx.hideLoading({
              success: (res) => {
                wx.showToast({
                  icon: 'none',
                  title: '账号已经存在，请重新输入',
                })
              },
            })
          }
  
        },
        fail(res) {
          console.log('10数据获取失败', res)
        }
      })
    },1000)

  },
  commitC() {
    var that = this
    wx.showLoading({
      title: '医师更改中...',
    })
    if (!this.data.doctorInfo.doctorName) {
      wx.showToast({
        icon: 'none',
        title: '医师姓名不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorId) {
      wx.showToast({
        icon: 'none',
        title: '医师id不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorPosition) {
      wx.showToast({
        icon: 'none',
        title: '医师职位不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorPay) {
      wx.showToast({
        icon: 'none',
        title: '预约费用不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorMaxPatient) {
      wx.showToast({
        icon: 'none',
        title: '可约人数不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorStartTime) {
      wx.showToast({
        icon: 'none',
        title: '开始时间不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorEndTime) {
      wx.showToast({
        icon: 'none',
        title: '结束时间不能为空',
      })
      return
    }
    if (!this.data.doctorInfo.doctorExpertise) {
      wx.showToast({
        icon: 'none',
        title: '医师专长不能为空',
      })
      return
    }
    if (this.data.doctorInfo.doctorPic.length == 0) {
      wx.showToast({
        icon: 'none',
        title: '医师图片不能为空',
      })
      return
    }
    wx.cloud.callFunction({
      name: "doctorInfo",
      data: {
        action: "change",
        doctorName: that.data.doctorInfo.doctorName,
        doctorId: that.data.doctorInfo.doctorId,
        doctorPosition: that.data.doctorInfo.doctorPosition,
        doctorPay: parseFloat(that.data.doctorInfo.doctorPay),
        doctorMaxPatient: parseInt(that.data.doctorInfo.doctorMaxPatient, 10),
        doctorStartTime: that.data.doctorInfo.doctorStartTime,
        doctorEndTime: that.data.doctorInfo.doctorEndTime,
        doctorExpertise: that.data.doctorInfo.doctorExpertise,
        doctorPic: that.data.doctorInfo.doctorPic,
        userDoctorAdmin: that.data.doctorInfo.userDoctorAdmin,
      }
    }).then(res => {
      console.log('21修改医师信息成功', res)
      //修改之后的提交标志变为true
      that.setData({
        isCommit: true
      })
      console.log('提交后的isCommit是', that.data.isCommit)
      wx.hideLoading({
        success: (res) => {
          wx.showToast({
            title: '更改医师成功',
          })
          setTimeout(function () {
            wx.navigateBack({})
          }, 1000)
        },
      })
    }).catch(res => {
      console.log('21医师信息更改失败', res)
      wx.hideLoading({
        success: (res) => {
          wx.showToast({
            icon: 'none',
            title: '更改医师失败',
          })
        },
      })
    })
  }
})